package wujinye.com.controller.user;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import wujinye.com.constant.Const;
import wujinye.com.controller.BaseServlet;
import wujinye.com.model.User;
import wujinye.com.model.UserFocus;
import wujinye.com.model.UserInfo;
import wujinye.com.service.UserService;
import wujinye.com.service.impl.UserServiceImpl;
import wujinye.com.utils.StrUtil;

import javax.jws.WebService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Struct;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    /**
     * 上传头像的文件到指定目录下
     *
     * @param req
     * @param resp
     */
    public void uploadFile(HttpServletRequest req, HttpServletResponse resp) {
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        servletFileUpload.setSizeMax(1024 * 1024 * 20L);
        try {
            // 接收前端传来的数据
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            FileItem item = fileItems.get(0);
            String[] split = item.getName().split("\\.");
            if (split.length == 2) {
                // 新建文件名
                String fileName = StrUtil.getUUID() + "." + split[1];
                // 文件地址
                String filePath = Const.BASE_FILEPATH + Const.PATH + fileName;
                File file = new File(filePath);
                if (!file.exists()) {
                    item.write(file);
                }
                // 更新数据中用户pic的值
                String userId = req.getSession().getAttribute("userId").toString();
                String path = Const.PATH + fileName;
                userService.updatePic(Integer.parseInt(userId), path);

                // 更新会话域中userBaseInfo的Map的值，再次进行数据库查找
                Map<String, Object> map = userService.findUserById(Integer.parseInt(userId));
                req.getSession().setAttribute("userBaseInfo", map);
                resp.getWriter().write(path);
            } else {
                resp.getWriter().write("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新用户信息
     *
     * @param req
     * @param resp
     */
    public void updateUserInfo(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 前4个，没输入则为""空
            // 后2个，没选则为null
            // sex：男-0，女-1，不选-null
            // secret：是-"on"，否-null
            String username = req.getParameter("username");
            String dept = req.getParameter("dept");
            String phone = req.getParameter("phone");
            String age = req.getParameter("age");
            String sex = req.getParameter("sex");
            String secret = req.getParameter("secret");
            Integer userId = StrUtil.stringToInteger(req.getSession().getAttribute("userId").toString());
            Map<String, Object> map = (Map<String, Object>) req.getSession().getAttribute("userBaseInfo");
            if (StrUtil.checkString(secret)) {
                secret = "1";
            } else {
                secret = "0";
            }
            User user = new User();
            user.setIsSecret(secret);
            user.setId(userId);
            if (StrUtil.checkString(dept)) {
                user.setDeptId(Integer.parseInt(dept));
            }
            userService.updateSecret(user);
            if (StrUtil.checkString(username) || StrUtil.checkString(phone) || StrUtil.checkString(age) || StrUtil.checkString(sex)) {
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(userId);
                userInfo.setRealName(StrUtil.emptyToNull(username));
                userInfo.setAge(StrUtil.stringToInteger(age));
                userInfo.setPhone(StrUtil.emptyToNull(phone));
                userInfo.setGender(StrUtil.emptyToNull(sex));
                userService.updateUserInfo(userInfo);
            }
            Map<String, Object> userMap = userService.findUserById(user.getId());
            req.getSession().setAttribute("userBaseInfo", userMap);
            resp.getWriter().write("success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看用户列表,分页,模糊查询
     *
     * @param req
     * @param resp
     */
    public void lookUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String search = req.getParameter("search");
            String currentPage = req.getParameter("currentPage");
            int page = 1;
            if (StrUtil.checkString(currentPage)) {
                page = Integer.parseInt(currentPage);
            }
            if (StrUtil.checkString(search)) {
                String encode = URLEncoder.encode(search, "UTF-8");
                resp.sendRedirect(req.getContextPath() + "/view/userList?page=" + page + "&search=" + encode);
            } else {
                resp.sendRedirect(req.getContextPath() + "/view/userList?page=" + page);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 实现关注用户操作
     *
     * @param req
     * @param resp
     */
    public void follow(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String userId = req.getSession().getAttribute("userId").toString();
            String ufId = req.getParameter("ufId");
            if (StrUtil.checkString(userId) && StrUtil.checkString(ufId)) {
                if (userId.equals(ufId)) {
                    resp.getWriter().write("不能关注自己！！！");
                } else {
                    // 先查找数据库中是否已有该组数据
                    UserFocus userFocus = userService.findFocusBean(StrUtil.stringToInteger(userId), StrUtil.stringToInteger(ufId));
                    if (userFocus == null) {
                        // 如果为空则添加数据
                        userService.addFocus(StrUtil.stringToInteger(userId), StrUtil.stringToInteger(ufId));
                        resp.getWriter().write("success");
                    } else {
                        resp.getWriter().write("关注失败");
                    }
                }
            } else {
                resp.getWriter().write("关注失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 实现取关用户操作
     *
     * @param req
     * @param resp
     */
    public void unfollow(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String userId = req.getSession().getAttribute("userId").toString();
            String ufId = req.getParameter("ufId");
            if (StrUtil.checkString(userId) && StrUtil.checkString(ufId)) {
                userService.removeFocus(StrUtil.stringToInteger(userId), StrUtil.stringToInteger(ufId));
                resp.getWriter().write("success");
            } else {
                resp.getWriter().write("取关失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * my_user.jsp页面的操作
     * @param req
     * @param resp
     */
    public void myFocus(HttpServletRequest req,HttpServletResponse resp){
        try {
            String pageCurrent = req.getParameter("page");
            int page = 1;
            if (StrUtil.checkString(pageCurrent)){
                page = Integer.parseInt(pageCurrent);
            }
            resp.sendRedirect(req.getContextPath()+"/view/myFocusList?page="+page);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
